package com.geek.javase.ch16.work.work3;

/*
 *@author wangpeng
 *2025/11/2
 *@description TODO
 */
/**
 * 静态内部类 vs DCL 单例模式对比测试
 */
public class SingletonTest {

    public static void main(String[] args) {
        // 1. 基础对比测试
        basicComparison();

        // 2. 多线程安全性对比
        threadSafetyComparison();
    }

    /**
     * 基础功能对比测试
     */
    private static void basicComparison() {
        System.out.println("=== 基础功能对比 ===");

        // 静态内部类单例
        Singleton staticSingleton1 = Singleton.getInstance();
        Singleton staticSingleton2 = Singleton.getInstance();
        System.out.println("静态内部类 - 同一实例: " + (staticSingleton1 == staticSingleton2));

        // DCL单例
        SingletonDCL dclSingleton1 = SingletonDCL.getInstance();
        SingletonDCL dclSingleton2 = SingletonDCL.getInstance();
        System.out.println("DCL单例 - 同一实例: " + (dclSingleton1 == dclSingleton2));

        System.out.println();
    }

    /**
     * 多线程安全性对比测试
     */
    private static void threadSafetyComparison() {
        System.out.println("=== 多线程安全性对比 ===");

        int threadCount = 5;

        // 测试静态内部类单例
        testStaticInnerClass(threadCount);

        // 测试DCL单例
        testDCL(threadCount);
    }

    /**
     * 测试静态内部类单例的线程安全性
     */
    private static void testStaticInnerClass(int threadCount) {
        System.out.println("静态内部类单例测试:");

        Thread[] threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(() -> {
                Singleton instance = Singleton.getInstance();
                System.out.println(Thread.currentThread().getName() + " - 实例: " + instance.hashCode());
            });
            threads[i].start();
        }

        // 等待所有线程完成
        waitForThreads(threads);
    }

    /**
     * 测试DCL单例的线程安全性
     */
    private static void testDCL(int threadCount) {
        System.out.println("DCL单例测试:");

        Thread[] threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(() -> {
                SingletonDCL instance = SingletonDCL.getInstance();
                System.out.println(Thread.currentThread().getName() + " - 实例: " + instance.hashCode());
            });
            threads[i].start();
        }

        // 等待所有线程完成
        waitForThreads(threads);
    }

    /**
     * 等待所有线程执行完成
     */
    private static void waitForThreads(Thread[] threads) {
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println();
    }
}